
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_mutex_t mutex_a = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_b = PTHREAD_MUTEX_INITIALIZER;

void *fun_a(void *arg)
{

    pthread_mutex_lock(&mutex_a);
    sleep(1);
    printf("pthread a wait lock b!\n");
    pthread_mutex_lock(&mutex_b);

    pthread_mutex_unlock(&mutex_a);
    pthread_mutex_unlock(&mutex_b);

    return (void *)0;
}

void *fun_b(void *arg)
{
    pthread_mutex_lock(&mutex_b);
    sleep(1);
    printf("pthread a wait lock a!\n");
    pthread_mutex_lock(&mutex_a);

    pthread_mutex_unlock(&mutex_b);
    pthread_mutex_unlock(&mutex_a);

    return (void *)0;
}

int main()
{
    pthread_t pid_a, pid_b;

    pthread_create(&pid_a, NULL, fun_a, NULL);
    pthread_create(&pid_b, NULL, fun_b, NULL);

    pthread_join(pid_a, NULL);
    pthread_join(pid_b, NULL);

    return 0;
}